package com.dailyblue.java.cloud.gateway.asserts;

import com.dailyblue.java.cloud.gateway.config.AgeConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
@Slf4j
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeConfig> {
    public AgeRoutePredicateFactory() {
        super(AgeConfig.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(AgeConfig config) {
        int maxAge = config.getMaxAge();
        int minAge = config.getMinAge();
        log.info("apply:maxAge:{},minAge:{}", maxAge, minAge);
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange swe) {
                int age = Integer.parseInt(swe.getRequest().getQueryParams().getFirst("age"));
                log.info("age:{}", age);
                return age > minAge && age < maxAge;
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minAge", "maxAge");
    }
}
